package com.mxsoft.concurrent;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    private Lock lock = new ReentrantLock();

    private void method(Thread thread) {
        if (lock.tryLock()) {
            try {
                System.out.println("线程名"+thread.getName()+"获得了锁");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("线程名"+thread.getName()+"释放了锁");
                lock.unlock();
            }
        } else {
            System.out.println("我是"+Thread.currentThread().getName()+"有人占这锁， 我就不要了");
        }
    }

    public static void main(String[] args) {

        LockTest lockTest = new LockTest(); 

        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lockTest.method(Thread.currentThread());
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lockTest.method(Thread.currentThread());
            }
        }).start();

        countDownLatch.countDown();
        countDownLatch.countDown();


    }

}
